<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('ROOT_PATH', dirname(__FILE__));
define('FRAMEWORK_PATH', ROOT_PATH . '/framework');
define('PROTECTED_PATH', ROOT_PATH . '/protected');
define('APP_PATH', PROTECTED_PATH . '/api');
define('MODEL_PATH', PROTECTED_PATH . '/model');
require_once(PROTECTED_PATH . '/config.php');
require_once(FRAMEWORK_PATH . '/global.php');
require_once(FRAMEWORK_PATH . '/wenyan.php');
require_once(APP_PATH . '/core.php');
require_once(APP_PATH . '/order.php');
require_once(MODEL_PATH . '/base.model.php');
require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');

$wxapi = new wechatCallbackAPI();
//$wxapi->valid(); //验证

$callback = NULL;
$act = (isset($_GET['act']) && trim($_GET['act'])) ? trim($_GET['act']) : '';
if (in_array($act, array('weixin_auth', 'mp_auth', 'component_auth', 'getcode', 'get_session_key'))) {
	$callback = $act;
	if ($act=='weixin_auth') $callback = NULL;
}
$wxapi->responseMsg($callback); //获取事件推送

//授权登录后执行
function mp_auth($json){
	global $wxapi, $db, $tbp;
}

//公众号授权给第三方开发平台后执行
function component_auth($json){
	global $wxapi, $db, $tbp;
	//$access_token = $json['authorizer_access_token'];
	//保存拉取到的公众号appid、原始id
	if (isset($_SESSION['member'])) {
		$appid = $json['authorizer_appid'];
		$userinfo = $wxapi->authorizer_userinfo($appid);
		$origin_id = $userinfo['authorizer_info']['user_name'];
		$sql = "SELECT brand_id FROM {$tbp}member WHERE id='".$_SESSION['member']->id."'";
		$brand_id = $db->get_var($sql);
		$sql = "UPDATE {$tbp}brand SET appid='{$appid}', `origin_id`='{$origin_id}' WHERE id='{$brand_id}'";
		$wxapi->log($sql);
		$db->query($sql);
		header("location:/brand/index.php?app=brand_index&act=index&component_auth=component_auth");
		exit;
	}
}

//APP端传递code过来换取access_token与获取用户资料
function getcode($json){
	global $wxapi, $db, $tbp;
	$member_id = isset($_GET['member_id']) ? intval($_GET['member_id']) : 0;
	if (!$member_id) {
		$error = array('errcode'=>10001, 'errmsg'=>'lost member id');
		exit(json_encode($error));
	}
	$md5 = $wxapi->md5_userinfo($json);
	//$wxapi->log(json_encode($json));
	//$wxapi->log($md5);
	//把微信昵称更新到会员表
	mysql_query("SET NAMES 'utf8mb4'");
	$sql = "UPDATE {$tbp}member SET wx_name='".$json['nickname']."', `md5`='{$md5}' WHERE id='{$member_id}'";
	$db->query($sql);
	$data = array('md5'=>$md5);
	exit(json_encode($data));
}

//小程序传递code过来换取access_token与openid
function get_session_key($json){
	exit(json_encode($json));
}

//关注
function subscribe($toUserName, $fromUserName){
	global $wxapi, $db, $tbp, $notify;
	//$url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	//$urls = explode('?', $url);
	//$url = $urls[0]."?weixin_auth=aes";
	//$wxapi->sendTextMsg($fromUserName, $toUserName, '请<a href="'.$url.'">点击这里</a>进行授权登录');
	if (WX_IS_THIRD) {
		$json = $wxapi->authorizer_access_token('', $toUserName);
		//$wxapi->log(json_encode($json));
		$json = $wxapi->get_userinfo($json['authorizer_access_token'], $fromUserName);
		$wxapi->log(json_encode($json));
		$md5 = $wxapi->md5_userinfo($json);
		$sql = "SELECT * FROM {$tbp}member WHERE md5='{$md5}'";
		$wxapi->log($sql);
		$member = $db->get_row($sql);
		$wxapi->log(json_encode($member));
		if ($member) {
			//把微信昵称更新到会员表
			mysql_query("SET NAMES 'utf8mb4'");
			$sql = "UPDATE {$tbp}member SET wx_name='".$json['nickname']."' WHERE id='{$member->id}'";
			$db->query($sql);
			//关注后操作
			$sql = "SELECT id FROM {$tbp}brand WHERE origin_id='{$toUserName}'";
			$wxapi->log($sql);
			$brand_id = $db->get_var($sql);
			$sql = "SELECT o.*, mf.id as focus_id FROM {$tbp}order o
				LEFT JOIN {$tbp}member_focus mf ON mf.order_id=o.id 
				WHERE mf.member_id='{$member->id}' AND mf.brand_id='{$brand_id}' AND o.status='3' AND is_focus='0' 
				AND now_people<hope_people ORDER BY o.id DESC";
			$order = $db->get_row($sql);
			$wxapi->log($sql);
			$wxapi->log(json_encode($order));
			if ($order) {
				//关注表修改状态
				$sql = "UPDATE {$tbp}member_focus SET is_focus='1', focus_time='".time()."' WHERE id='{$order->focus_id}'";
				$db->query($sql);
				//为会员增加关注报酬
				//配置参数
				$sql = "SELECT content FROM {$tbp}config WHERE name='min_focus_money' OR name='max_focus_money' ORDER BY id DESC";
				$money = $db->get_results($sql);
				//根据备置参数随机拿到关注佣金
				$focus_money = substr($money[1]->content + mt_rand()/mt_getrandmax() * ($money[0]->content-$money[1]->content) , 0 ,3);
				$sql = "UPDATE {$tbp}member SET money=money+{$focus_money} WHERE id='{$member->id}'";
				$db->query($sql);
				//$wxapi->log($sql);
				//增加收入明细
				$sql = "INSERT INTO {$tbp}financial_detail (type, member_id, money, brand_id , add_time) 
					VALUES ('3', '{$member->id}', '{$focus_money}', '{$order->brand_id}' ,'".time()."')";
				$db->query($sql);
				$wxapi->log($sql);
				//订单当前关注人数增加人，且判断是否已够期望关注人数，如果够即修改状态
				$status = 3;
				$now_people = $order->now_people + 1;
				if ($now_people>=$order->hope_people) $status = -1;
				$sql = "UPDATE {$tbp}order SET now_people='{$now_people}', status='{$status}' WHERE id='{$order->id}'";
				$db->query($sql);
				//如果满足订单完成条件而且没有其他推广订单，设为入驻订单，不让关注单可显示
				if($status == -1){
					$sql = "SELECT id FROM {$tbp}order WHERE  brand_id = '{$order->brand_id}' AND status = 3";
					$val = $db->get_results($sql);
					if(!$val){
						//入驻订单
						$sql = "UPDATE {$tbp}order SET status= 1 WHERE id='{$order->id}'";
						$db->query($sql);
					}
				}
				//发送推送
				if ($member->udid!='') $notify->send($member->udid, "关注成功，恭喜你获得{$focus_money}个多元币");
			}
		}
	}
	exit('success');
}

//取消关注
function unsubscribe($fromUserName){
	global $wxapi;
	exit('success');
}

//关键字回复
function msgText($content=''){
	global $wxapi;
	if ($content=='') return '';
	$matcher = '';
	/*
	preg_match_all('/(BL\d{5,6})/i', $content, $matchs);
	for($i=0; $i<count($matchs[0]); $i++){
		$m = $matchs[1][$i];
		$matcher = '';
		break;
	}
	*/
	return $matcher;
}

//默认自动回复
function autoReply(){
	global $wxapi;
	return '';
}

//扫描
function scan($id){
	global $wxapi;
	//$wxapi->log($id);
}
//随机生成小数
function randFloat($min=0, $max=1 ,$bit=1){
	$num =  $min + mt_rand()/mt_getrandmax() * ($max-$min);
	//截取一位
	$bit = $bit + 2;
	return substr($num, 0, $bit);
}
